#include "sm4.h"
#include <stdio.h>
#include <string.h>
#include <iostream>
#include "crypto.h"
using namespace std;

//无符号字符数组转16进制打印
void print_hex(unsigned char *data , int len)
{
    int i = 0;
    char alTmp[16] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    for(i = 0 ; i < len ; i++)
    {
        printf("%c" , alTmp[data[i]/16]);
        printf("%c" , alTmp[data[i]%16]);
    }
    putchar('\n');
}

int main(int argc, char *argv[])
{
    Crypto::init(); // 初化随机种子 

// 模拟协商 
    Crypto client;  // A 
    size_t* g_p = client.get_public(); // 生成 (g, p) 
    size_t X = client.get_pub_key();   // 计算 X 

    Crypto server(g_p[0], g_p[1]);     // B, 接收 (g, p)  
    size_t Y = server.get_pub_key();   // 计算 Y 
    char* K2 = server.get_key(X);      // B 计算会话密钥 
    char* K1 = client.get_key(Y);      // A 通过 B 发的 Y 计算会话密钥 
    if (argc != 2)
    {
        printf("Usage: sender text\n");
        return 0;
    }
    //对字符进行分包发送 16字符为一包
    for (int i = 0; i < strlen(argv[1]); i += 16)
    {
        int k = 0;
        unsigned char data[16] = { 0x00 }; //用结束符补够16
        for (int j = i; j < j + 16; ++j)
        {
            if (j > strlen(argv[1]) - 1)
                break;
            data[k++] = argv[1][j];
        }
        sm4_context ctx;
        sm4_setkey_enc(&ctx, (unsigned char *)K2);
        sm4_crypt_ecb(&ctx,
                      SM4_ENCRYPT,
                      16,
                      data,
                      data);
        print_hex(data, 16);
    }
    return 0;
}
